﻿using DeviceMonitor.Model;
using DeviceMonitor.Utils;
using DeviceMonitor.ViewModel;
using DeviceMonitor.Windows;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DeviceMonitor.Pages
{
    /// <summary>
    /// LoadRecordPage.xaml 的交互逻辑
    /// </summary>
    public partial class LoadRecordPage : Page
    {
        LoadViewModel viewModel;
        delegate void MyDelegate(Object value);
        SynchronizationContext _syncContext = null;

        public LoadRecordPage()
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;

            viewModel = new LoadViewModel();
            this.DataContext = viewModel;

            this.Loaded += Page_Loaded;
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            //datePicker.Text = DateTime.Now.ToString("yyyy-MM-dd");
            timeBegin.DateTimeStr = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
            timeEnd.DateTimeStr = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59";
            LoadData();
        }
        private void LoadData()
        {
            new Task(() =>
            {
                Invoke();
            }).Start();
        }
        String queryBeginTime = "";
        String queryEndTime = "";
        private void LoadRecordData()
        {
            queryBeginTime = timeBegin.DateTimeStr;
            queryEndTime = timeEnd.DateTimeStr;
            
            new Task(() =>
            {
                Invoke2();
            }).Start();
        }
        public async void Invoke()
        {
            try
            {
                String ip = App.GetConfig().HttpServerIp;
                String port = App.GetConfig().HttpServerPort;

                var result = HttpPostHelper.doHttpAsyncPost("http://" + ip + ":" + port + "/billing/queryList", "{}");
                string str = await result;  //等待返回

                MyDelegate d = new MyDelegate(dealLoadData);
                this.Dispatcher.Invoke(d, str);
            }
            catch (Exception ex) { }
        }
        public async void Invoke2()
        {
            try
            {
                String ip = App.GetConfig().HttpServerIp;
                String port = App.GetConfig().HttpServerPort;

                JObject paraJSON = new JObject();
                if (!"".Equals(queryBeginTime))
                {
                    paraJSON.Add("queryBeginTime", queryBeginTime);
                }
                if (!"".Equals(queryEndTime))
                {
                    paraJSON.Add("queryEndTime", queryEndTime);
                }
                var result = HttpPostHelper.doHttpAsyncPost("http://" + ip + ":" + port + "/loadRecord/queryRecordList", paraJSON.ToString());
                string str = await result;  //等待返回

                MyDelegate d = new MyDelegate((Object obj) => {
                    viewModel.LoadRecordData((string)obj);
                });
                this.Dispatcher.Invoke(d, str);
            }
            catch (Exception ex) { }
        }
        void dealLoadData(Object obj)
        {
            viewModel.LoadData((string)obj);
        }


        private void Button_Click_Query(object sender, RoutedEventArgs e)
        {
            LoadRecordData();
        }

        private void showLogChartWindow(object sender, MouseButtonEventArgs e)
        {
            Billing billing = (Billing)dataGrid01.SelectedItem;
            ChartWindow chartWindow = new ChartWindow();
            chartWindow.setId(billing.id);
            chartWindow.Owner = App.MainWindow;
            chartWindow.ShowDialog();
        }
        private void showLogChartWindow02(object sender, MouseButtonEventArgs e)
        {
            LoadRecord record = (LoadRecord)dataGrid02.SelectedItem;
            ChartWindow chartWindow = new ChartWindow();
            chartWindow.setId(record.billingId);
            chartWindow.Owner = App.MainWindow;
            chartWindow.ShowDialog();
        }

        private void Radio_Click_RealRecord(object sender, RoutedEventArgs e)
        {
            dataGrid01.Visibility = Visibility.Visible;
            dataGrid02.Visibility = Visibility.Hidden;
            conditionPanel.Visibility = Visibility.Hidden;
            createBillingPanel.Visibility = Visibility.Visible;
            LoadData();
        }

        private void Radio_Click_HisRecord(object sender, RoutedEventArgs e)
        {
            dataGrid01.Visibility = Visibility.Hidden;
            dataGrid02.Visibility = Visibility.Visible;
            conditionPanel.Visibility = Visibility.Visible;
            createBillingPanel.Visibility = Visibility.Hidden;
            LoadRecordData();
        }

        private void Button_Click_CreateBilling(object sender, RoutedEventArgs e)
        {
            BillingEditWindow billingEditWindow = new BillingEditWindow();
            billingEditWindow.Owner = App.MainWindow;
            bool result = (bool)billingEditWindow.ShowDialog();
            if (result)
            {
                LoadData();
            }
        }

        private void Button_Click_LoadData(object sender, RoutedEventArgs e)
        {
            LoadData();
        }

        private void deleteBilling_record(object sender, MouseButtonEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("是否删除?", "确认", MessageBoxButton.YesNo);
            if (result != MessageBoxResult.Yes) return;

            Billing billing = (Billing)dataGrid01.SelectedItem;

            new Task(() =>
            {
                try
                {
                    string param = JObject.FromObject(billing).ToString();
                    String response = HttpPostHelper.doHttpPost("/billing/delete", param);
                    JObject rspJson = JObject.Parse(response);
                    bool success = (bool)rspJson["success"];
                    if (success)
                    {
                        _syncContext.Post(removeRow, billing);
                    }
                    else
                    {
                        MessageBox.Show(rspJson["message"].ToString());
                    }
                }
                catch (Exception ex) { }
            }).Start();
        }
        private void removeRow(Object item)
        {
            viewModel.billingList.Remove((Billing)item);
        }
    }
}
